package com.blank.util;

import java.sql.*;

/**
 * @author blank
 * 2020-11-2
 */
public class DButil {


	/**
	 * 数据库驱动和地址
	 */

	static final String JDBC_DRIVER ="com.mysql.jdbc.Driver";
	static final String DB_URl ="jdbc:mysql://localhost:3306/bookmanager?useSSL=false";
	
	/**
	*数据库用户名和密码
	*/
	static final String  USER ="root";
	static final String PASS="root";
	
	//注册驱动
	static {
		try {
			Class.forName(JDBC_DRIVER);
		} catch (ClassNotFoundException e) {
			// TODO: handle exception
			System.out.println("注册驱动失败");
		}
	}
	private Connection conn;
	private Statement stat;
	private PreparedStatement pstmt;
	

	/**
	 * 打开连接
	 */

	private void openConnection() {
		try {
			conn=DriverManager.getConnection(DB_URl,USER,PASS);
			conn.setAutoCommit(false);
		}catch (SQLException e) {
			// TODO: handle exception
			System.out.println("数据库连接失败");
		}
	}


	/**
	 * 事务回滚
	 */
	public void connectionRollback() {
		try {
			conn.rollback();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			System.out.println("数据库回滚失败");
		}
	}


	/**
	 * 提交事务
	 */
	public void commit() {
		try {
			conn.commit();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			System.out.println("提交事务失败");
		}
	}

	/**
	 * statement
	 */
	public Statement getStatement() {
		openConnection();
		try {
			stat=conn.createStatement();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			System.out.println("获取statement失败");
		}
		return stat;
	}


	/**
	 * PrepaeredStatement
	 * @param sql
	 * @return
	 */
	public PreparedStatement getPreparedStatement (String sql) {
		openConnection();
		try {
			pstmt=conn.prepareStatement(sql);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return pstmt;
	}


	/**
	 * 关闭流
	 */
	public void colserResoure() {
		try {
			if (pstmt !=null && !pstmt.isClosed()) {
				pstmt.close();
			}
			if (stat != null && !stat.isClosed()) {
				stat.close();
			}

			if (conn != null && !conn.isClosed()) {
				conn.close();
			}
		} catch (SQLException e) {
			// TODO: handle exception
			e.printStackTrace();
		}
	}
}
